<template>
  <div class="home-container">
    <div class="page-header">
      <h1>球场列表</h1>
      <p>选择您想要预约的球场和时间段</p>
    </div>
    
    <div v-if="courtStore.loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else class="courts-grid">
      <el-card
        v-for="court in courtStore.courts"
        :key="court.id"
        class="court-card"
        shadow="hover"
      >
        <template #header>
          <div class="card-header">
            <h3>{{ court.name }}</h3>
            <el-tag :type="getCourtTypeTag(court.type)">
              {{ getCourtTypeName(court.type) }}
            </el-tag>
          </div>
        </template>
        
        <div class="court-content">
          <div class="court-image">
            <img :src="court.image_url" :alt="court.name" />
          </div>
          
          <div class="court-info">
            <p class="description">{{ court.description }}</p>
            
            <div class="time-slots">
              <h4>可预约时间段：</h4>
              <div class="slots-grid">
                <el-button
                  v-for="slot in court.time_slots"
                  :key="slot.id"
                  :type="slot.available ? 'primary' : 'info'"
                  :disabled="!slot.available"
                  size="small"
                  @click="openBookingDialog(court, slot)"
                  class="slot-button"
                >
                  {{ slot.time_range }}
                  <br>
                  ¥{{ slot.price }}
                </el-button>
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
    
    <!-- 预约对话框 -->
    <el-dialog
      v-model="bookingDialogVisible"
      title="预约球场"
      width="500px"
      :before-close="handleCloseBooking"
    >
      <div v-if="selectedCourt && selectedSlot">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="球场名称">
            {{ selectedCourt.name }}
          </el-descriptions-item>
          <el-descriptions-item label="时间段">
            {{ selectedSlot.time_range }}
          </el-descriptions-item>
          <el-descriptions-item label="价格">
            ¥{{ selectedSlot.price }}
          </el-descriptions-item>
          <el-descriptions-item label="预约日期">
            <el-date-picker
              v-model="bookingDate"
              type="date"
              placeholder="选择预约日期"
              :disabled-date="disabledDate"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="bookingDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :loading="bookingLoading"
            :disabled="!bookingDate"
            @click="handleBooking"
          >
            确认预约
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { useCourtStore } from '@/stores/court'
import dayjs from 'dayjs'

const courtStore = useCourtStore()

// 状态
const bookingDialogVisible = ref(false)
const selectedCourt = ref(null)
const selectedSlot = ref(null)
const bookingDate = ref('')
const bookingLoading = ref(false)

// 方法
const getCourtTypeName = (type) => {
  const typeMap = {
    basketball: '篮球场',
    badminton: '羽毛球场',
    tennis: '网球场'
  }
  return typeMap[type] || '其他'
}

const getCourtTypeTag = (type) => {
  const tagMap = {
    basketball: 'primary',
    badminton: 'success',
    tennis: 'warning'
  }
  return tagMap[type] || 'info'
}

const openBookingDialog = async (court, slot) => {
  if (!slot.available) {
    ElMessage.warning('该时间段已被预约')
    return
  }
  
  selectedCourt.value = court
  selectedSlot.value = slot
  bookingDate.value = ''
  bookingDialogVisible.value = true
}

const handleBooking = async () => {
  if (!bookingDate.value) {
    ElMessage.warning('请选择预约日期')
    return
  }
  
  bookingLoading.value = true
  try {
    const result = await courtStore.bookCourt(
      selectedCourt.value.id,
      selectedSlot.value.id,
      bookingDate.value
    )
    
    if (result.success) {
      ElMessage.success(result.message)
      bookingDialogVisible.value = false
      
      // 重新加载可用时间段
      await loadAvailableTimeSlots()
    } else {
      ElMessage.error(result.message)
    }
  } finally {
    bookingLoading.value = false
  }
}

const handleCloseBooking = () => {
  bookingDialogVisible.value = false
  selectedCourt.value = null
  selectedSlot.value = null
  bookingDate.value = ''
}

const disabledDate = (time) => {
  // 禁用过去的日期
  return time.getTime() < Date.now() - 8.64e7
}

const loadAvailableTimeSlots = async () => {
  if (!selectedCourt.value || !bookingDate.value) return
  
  try {
    const availableSlots = await courtStore.getAvailableTimeSlots(
      selectedCourt.value.id,
      bookingDate.value
    )
    
    // 更新选中球场的时间段可用性
    const court = courtStore.courts.find(c => c.id === selectedCourt.value.id)
    if (court) {
      court.time_slots = availableSlots
    }
  } catch (error) {
    console.error('加载可用时间段失败:', error)
  }
}

// 监听预约日期变化
watch(bookingDate, () => {
  if (bookingDate.value) {
    loadAvailableTimeSlots()
  }
})

onMounted(async () => {
  await courtStore.loadCourts()
})
</script>

<style scoped>
.home-container {
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.page-header h1 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 2rem;
}

.page-header p {
  margin: 0;
  color: #666;
  font-size: 1.1rem;
}

.loading-container {
  padding: 20px;
}

.courts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(400px, 1fr));
  gap: 20px;
}

.court-card {
  transition: transform 0.3s ease;
}

.court-card:hover {
  transform: translateY(-5px);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-header h3 {
  margin: 0;
  color: #333;
}

.court-content {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.court-image {
  width: 100%;
  height: 200px;
  overflow: hidden;
  border-radius: 8px;
}

.court-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.court-info {
  flex: 1;
}

.description {
  color: #666;
  margin: 0 0 15px 0;
  line-height: 1.5;
}

.time-slots h4 {
  margin: 0 0 10px 0;
  color: #333;
  font-size: 1rem;
}

.slots-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
  gap: 8px;
}

.slot-button {
  height: auto;
  padding: 8px 4px;
  font-size: 0.9rem;
  line-height: 1.2;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

@media (max-width: 768px) {
  .courts-grid {
    grid-template-columns: 1fr;
  }
  
  .slots-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}
</style>
